﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CRM.Models;
using CRM.ViewModels.Email;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace CRM.Controllers.Email
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmailSendFreeController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;

        public EmailSendFreeController(MyDbContext dbContext, UserManager<User> userManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
        }
        public record Tree(string Label, int Value, IEnumerable<Tree> Children);
        
        [HttpGet(nameof(GetInit))]
        public async Task<ResultStruct> GetInit()
        {
            var user = await _userManager.GetUserAsync(User);
            var model = _dbContext.EmailConfig.Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id);
            var tep = await model.ToListAsync();
            var groupIds = tep.Select(m => m.EmailConfigGroupId).Distinct();
            _ = await _dbContext.EmailConfigGroup
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                .Where(m => groupIds.Contains(m.Id))
                .ToListAsync(); 
            var temp = 
                _dbContext.EmailConfigGroup.Local
                    .AsQueryable()
                    .Include(m => m.EmailConfigs)
                    .Select(m => new {Label = m.Name, Value = m.Id, Children = m.EmailConfigs.Select(l => new {Label=l.EmailAddress, Value=l.Id})})
                    .ToList();
            temp = temp.Prepend(new {Label = "暂无分组", Value =0, Children = tep.Where(l => l.EmailConfigGroupId == 0).Select(l => new {Label = l.EmailAddress, Value=l.Id })}).ToList();

            return Success(new { listOfAuthorizedMailbox = temp });
            // return Success();
        }
        
        [HttpPost(nameof(Create))]
        public async Task<ResultStruct> Create(EmailMarketingVM vm)
        {
            await Task.Run(()=>{});
            return Success();
            // var emailConfig = await _dbContext.EmailConfig.FindAsync(vm.Addresser);
            // try{
            //     var config = new ConfigurationRoot(new List<IConfigurationProvider>() { });
            //     var renderer = RazorRendererFactory.MakeInstance(config);
            //     var smtpMailer = new SmtpMailer(renderer, emailConfig.Host, emailConfig.Port, emailConfig.EmailAddress,
            //         emailConfig.Secret);
            //     await smtpMailer.SendAsync(vm.EmailContent, vm.EmailSubject, vm.AddresseeRecipient, emailConfig.EmailAddressRecipient, null, null,
            //         null, null);
            //     return Success();
            // }catch(Exception e)
            // {
            //     return Error(e.Message);
            // }


            // if (!ModelState.IsValid) return Error(message: ModelState.ToString());
            // var model = vm.NewModel();
            // await _dbContext.EmailSendHistory.AddAsync(model);
            // await _dbContext.SaveChangesAsync();
        }

        // [HttpGet(nameof(Index))]
        // public async Task<ResultStruct> Index()
        // {
        //     return Success(await _dbContext.EmailSendFree.ToPaginateAsync());
        // }
        //
        // [HttpGet(nameof(SendingFree))]
        // public async Task<ResultStruct> SendingFree()
        // {
        //     return Success(await _dbContext.EmailSendFree.Where(m => m.SendingType == EmailSendFree.SendingTypeEnum.Free).ToPaginateAsync());
        // }        
        //
        // [HttpGet(nameof(SendingByServer))]
        // public async Task<ResultStruct> SendingByServer()
        // {
        //     return Success(await _dbContext.EmailSendFree.Where(m => m.SendingType == EmailSendFree.SendingTypeEnum.Server).ToPaginateAsync());
        // }


        // // GET
        // [HttpPost(nameof(Create))]
        // public async Task<ResultStruct> Create(EmailSendFreeCreateVM vm)
        // {
        //     if (!ModelState.IsValid) return Error(message: ModelState.ToString());
        //     var model = vm.NewModel();
        //     System.Console.WriteLine(model);
        //     await _dbContext.EmailSendFree.AddAsync(model);
        //     await _dbContext.SaveChangesAsync();
        //     return Success();
        // }

        // [HttpGet(nameof(Info))]
        // public async Task<ResultStruct> Info([FromQuery] int id)
        // {
        //     return Success(await _dbContext.EmailSendFree.FindAsync(id));
        // }
    }
}